// src/utils/websocket.js
class WebSocketManager {
  constructor(url) {
    this.url = url;
    this.socket = null;
    this.listeners = {};
  }

  // 初始化 WebSocket 连接
  connect() {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      console.log("WebSocket is already connected.");
      return;
    }

    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      this.emit("open");
    };

    this.socket.onmessage = (event) => {
      console.log("监听到消息", event.data);
      let data = JSON.parse(event.data);
      console.log(data, 666);
      window.agentId = data.agent; // 存储到全局变量
      this.emit("message", event.data);
    };

    this.socket.onerror = (error) => {
      console.error("WebSocket error:", error);
      this.emit("error", error);
    };

    this.socket.onclose = () => {
      console.log("WebSocket connection closed.");
      this.emit("close");
    };
  }

  // 发送消息
  send(data) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(data);
    } else {
      console.error("WebSocket is not open.");
    }
  }

  // 关闭 WebSocket 连接
  close() {
    if (this.socket) {
      this.socket.close();
    }
  }

  // 添加事件监听器
  on(event, callback) {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event].push(callback);
  }

  // 触发事件
  emit(event, data) {
    if (this.listeners[event]) {
      this.listeners[event].forEach((callback) => callback(data));
    }
  }
}
// 将实例存储到全局变量
if (!window.WebSocketManagerInstance) {
  window.WebSocketManagerInstance = null;
}
export default WebSocketManager;
